import { UITransform, _decorator } from "cc";
import { ENTITY_STATE_ENUM, EVENT_ENUM } from "../../Enums";
import EventManager from "../../Runtime/EventManager";
import DataManager from "../../Runtime/DataManager";
import { IEntity } from "../../Levels";
import { EntityManager } from "../../Base/EntityManager";
import { BurstStateMachine } from "./BurstStateMachine";
import { TILE_HIGHT, TILE_WIDTH } from "../Tile/TileManager";

const { ccclass, property } = _decorator


@ccclass('BurstManager')
export class BurstManager extends EntityManager {

  async init(params:IEntity) {
    this.fsm = this.addComponent(BurstStateMachine)
    await this.fsm.init()
    super.init(params)
    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_WIDTH, TILE_HIGHT)

    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst, this)
  }

  onDestroy() {
    super.destroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst)
  }

  update() {
    this.node.setPosition(this.x * TILE_WIDTH, -this.y * TILE_HIGHT)
  }

  onBurst() {
    if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) {
      return
    }
    const {x:playerX, y:playerY} = DataManager.Instance.player
    if (this.x === playerX && this.y === playerY && this.state === ENTITY_STATE_ENUM.IDLE) {
      this.state = ENTITY_STATE_ENUM.ATTACK
    } else if (this.state === ENTITY_STATE_ENUM.ATTACK) {
      console.log('state is ATTACK')
      this.state = ENTITY_STATE_ENUM.DEATH
      if (this.x === playerX && this.y === playerY) {
        console.log('emit attack player')
        EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.AIRDEATH)
      }
    }
  }
}
